/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package org.luxor.generator.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import org.apache.commons.io.IOUtils;
import org.luxor.commons.jdbc.annotation.DS;
import org.luxor.generator.dao.GeneratorDao;
import org.luxor.generator.utils.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service
@DS("#session.datasource")
public class SysGeneratorService {

    @Resource
    private SysProjectModelService projectModelService;

    @Resource
    private GeneratorDao generatorDao;

    public PageUtils queryList(Query query) {
        Page<?> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<Map<String, Object>> list = generatorDao.queryList(query);

        return new PageUtils(list, (int) page.getTotal(), query.getLimit(), query.getPage());
    }

    public Map<String, String> queryTable(String tableName) {
        return generatorDao.queryTable(tableName);
    }

    public List<Map<String, String>> queryColumns(String tableName) {
        return generatorDao.queryColumns(tableName);
    }

    public byte[] generatorCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for (String tableName : tableNames) {
            //查询表信息
            Map<String, String> table = queryTable(tableName);
            //查询列信息
            List<Map<String, String>> columns = queryColumns(tableName);
            //生成代码
            GenCodeUtils.generatorCode(projectModelService.info(), projectModelService.getTypeMappings(), table, columns, zip);
        }

        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    public byte[] generatorWord(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            //生成文档
            Document document = GenWordUtils.createWord(outputStream);
            for (String tableName : tableNames) {
                //查询表信息
                Map<String, String> table = queryTable(tableName);
                //查询列信息
                List<Map<String, String>> columns = queryColumns(tableName);
                //添加表设计
                GenWordUtils.addTable(document, table, columns);
            }
            document.close();
            return outputStream.toByteArray();
        } catch (DocumentException e) {
            throw new RRException("生产word模板失败", e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }

    }
}
